package com.wyj.springmvc.framework.pojo;


import com.wyj.springmvc.framework.annotation.Security;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * TODO: security注解所在类的代理类
 *
 * @author wuyijie
 * @date 2021/11/24 4:21 下午
 */
public class SecurityProxy {
    private final Object target;

    public SecurityProxy(Object target) {
        this.target = target;
    }

    /**
     * TODO: 获取代理对象。username进行权限判断。
     *
     * @param username 入参
     * @return java.lang.Object
     * @author wuyijie
     * @date 2021/11/24 4:29 下午
     */
    public Object getCglibProxy(String username) {
        return Enhancer.create(target.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Security annotation = null;
                List<String> securityValues;

                //判断方法上是否有权限注解。有的话，忽略掉类上的权限注解。
                if (method.isAnnotationPresent(Security.class)) {
                    annotation = method.getAnnotation(Security.class);
                }
                //再判断类上面是否有权限注解
                else if (target.getClass().isAnnotationPresent(Security.class)) {
                    annotation = target.getClass().getAnnotation(Security.class);
                }
                securityValues = annotation != null ? Arrays.asList(annotation.values()) : new ArrayList<>();
                System.out.println(securityValues);
                //需要进行权限判断
                if (!securityValues.isEmpty()) {
                    if (null == username || username.length() == 0 || !securityValues.contains(username)) {
                        return "亲，你没有权限访问哦···";
                    }
                }

                System.out.println("进入cglib代理···");
                Object invoke = method.invoke(target, objects);
                System.out.println("结束cglib代理···");
                return invoke;
            }
        });
    }
}
